#!/usr/bin/python3.5

import sys
import ghost
import json

user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 \
(KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'

pc_user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/58.0.3029.110 Safari/537.36HH=15Runtime=kecekldmfbcpjfmnnijdjhcggpcnkpbhALICDN/ DOL/HELLO_GWF_s_5356_r2x9ak474125_832'

def track(url):
    timeout = 15
    for _ in range(3):
        try:
            return _track(url, timeout=timeout)
        except ghost.ghost.TimeoutError as e:
            timeout += 10

def _track(url, timeout):
    gh = ghost.Ghost(log_level=51)
    session = ghost.Session(
        ghost=gh, user_agent=pc_user_agent, wait_timeout=timeout,
        display=False, plugins_enabled=False, download_images=False)

    page, _ = session.open(url)

    session.page = None
    goodsData = session.evaluate('''
            var textAreaList = document.getElementsByClassName('media-text-area');
            var qingTaokeData = [];
            for(var i = 0; i < textAreaList.length; i++){
                var p = textAreaList[i].getElementsByTagName('p');
                if(p.length == 5){
                    var itemData = {
                        guid_content : textAreaList[i].getElementsByTagName('p')[4].innerText,
                        goods_url : textAreaList[i].getElementsByTagName('p')[3].getElementsByTagName('a')[0].getAttribute('href'),
                        coupon_url : textAreaList[i].getElementsByTagName('p')[2].getElementsByTagName('a')[0].getAttribute('href')
                    };
                    qingTaokeData.push(itemData);
                }else{
                    var itemData = {
                        guid_content : textAreaList[i].getElementsByTagName('p')[3].innerText,
                        goods_url : textAreaList[i].getElementsByTagName('p')[2].getElementsByTagName('a')[0].getAttribute('href')
                    };
                    qingTaokeData.push(itemData);
                }
            }
            
            JSON.stringify(qingTaokeData)
       ''')

    print (goodsData[0])


    sys.stdout.flush()
    session.exit()
    gh.exit()


if __name__ == '__main__':
    track(sys.argv[1])
